# -*- coding: utf-8 -*-

"""
@author: bw
@contact: bw@handsdriver.net
"""

__all__ = ('loadZCML',)

import os
import importlib

import eof.log as log

from . import ifaces
from . import shortcuts as ztk


def loadFallbackIfRequired():
	if not ztk.queryInterface(ifaces.IEofZtk.__identifier__):
		package_name = __package__.split('.', 1)[0]
		ztk.loadZCML(package_name + ':fallback.zcml')


def loadZCML(zcml, devmode=None):
	def include_zcml(ctx, zcml):
		if not isinstance(zcml, str):
			zcml = zcml.__package__

		if '\n' not in zcml and os.path.isfile(zcml):
			log.debug('Include ZCML: {filename}', filename=zcml)
			return ztk.xmlconfig.file(zcml, context=ctx, execute=False)

		if '\n' not in zcml and ':' not in zcml:
			try:
				importlib.import_module(zcml)
			except ImportError:
				pass
			else:
				zcml += ':configure.zcml'

		if '\n' not in zcml and zcml.count(':') == 1:
			package, zcmlpath = zcml.split(':')
			package = importlib.import_module(package)
			log.debug('Include ZCML: {filename} ({package})', filename=zcmlpath, package=package.__name__)
			return ztk.xmlconfig.file(zcmlpath, package, context=ctx, execute=False)

		log.debug('Include ZCML string')

		return ztk.xmlconfig.string(zcml, context=ctx, execute=False)

	zcml_ctx = ztk.xmlconfig.ConfigurationMachine()
	ztk.xmlconfig.registerCommonDirectives(zcml_ctx)

	if devmode is True:
		zcml_ctx.provideFeature('devmode')

#	with log.disable('config'):
	if type(zcml) in (tuple, list):
		for item in zcml:
			zcml_ctx = include_zcml(zcml_ctx, item)
	else:
		zcml_ctx = include_zcml(zcml_ctx, zcml)

	zcml_ctx.execute_actions(clear=True)
